Invalid Type Cast Or Check (ITCOC)

Description:

ITCOC inspects type cast and type check ( is ) expressions. It produces a message when the runtime type of an expression (computed by dataflow analysis) is not compatible with the target type. At runtime, such type casts will result in throwing an invalid type cast exception and type checks will always return false.

Not compatible here means that neither the actual type of the expression is the same or is a subclass of the target type of type cast or type check operator, nor is the target type a subclass of the expression type and there is no class or interface that is the common ancestor for both expression and target types.

If the option ErrorsOnly is set in the audit properties, the last condition (common successor) is skipped and a message is produced in all cases where the target type is not related with the expression type (in other words, they are not on the same path in the inheritance graph). Such a message does not always mean that there is a runtime error, but in most cases, it is caused by incorrect design or usage of the class hierarchy. By default, the option ErrorsOnly is set, so that only messages for conversions that always cause exceptions being thrown at runtime are produced.

Incorrect:

class A { 
    public void Print() {
    } 
}

class B {
    public void Print() {
    } 
}

void Print(object obj) { 
    if (obj is A) { // runtime type of obj is now A 
        ((B) obj).Print(); // type cast will cause exception at runtime
                           // because obj can not be of type B
    }
}    

Correct:

class A { 
    public void Print() {
    } 
}

class B {
    public void Print() {
    } 
}

void Print(object obj) { 
    if (obj is A) {
        ((A) obj).Print();
    }
}